import { ConfigManager } from './ConfigManager';
import { PlatformAdapter } from './PlatformAdapter';
import { ErrorCollector } from './ErrorCollector';
import { ErrorReporter } from './ErrorReporter';
import { ErrorLevel, PlatformType } from '../types'; // 添加PlatformType导入
import type { SDKConfig, ErrorInfo } from '../types';

export class UniErrorSDK {
  private configManager: ConfigManager;
  private platformAdapter: PlatformAdapter;
  private errorCollector: ErrorCollector;
  private errorReporter: ErrorReporter;
  private isInitialized = false;

  constructor(config: SDKConfig) {
    this.configManager = new ConfigManager(config);
    
    // 将用户指定的平台类型转换为内部枚举
    let platformType: PlatformType | undefined; // 改为PlatformType
    if (config.platform) {
      switch (config.platform) {
        case 'App':
          platformType = PlatformType.App; // 修正：使用正确的枚举值
          break;
        case 'MpWeixin':
          platformType = PlatformType.MpWeixin; // 修正：使用正确的枚举值
          break;
        case 'H5':
          platformType = PlatformType.H5;
          break;
      }
    }
    
    this.platformAdapter = new PlatformAdapter(platformType);
    this.errorCollector = new ErrorCollector(this.configManager, this.platformAdapter);
    this.errorReporter = new ErrorReporter(this.configManager, this.platformAdapter);
  }

  /**
   * 初始化SDK
   */
  async init(): Promise<void> {
    if (this.isInitialized) {
      console.warn('[UniErrorSDK] SDK已经初始化');
      return;
    }

    try {
      // 初始化平台适配器
      await this.platformAdapter.init();
      
      // 预先获取设备信息以验证平台API可用性
      await this.platformAdapter.getDeviceInfo();
      
      // 初始化错误收集器
      await this.errorCollector.init();
      
      // 初始化错误上报器
      await this.errorReporter.init();
      
      this.isInitialized = true;
      
      if (this.configManager.getConfig().enableConsoleLog) {
        console.log('[UniErrorSDK] 初始化成功');
      }
    } catch (error) {
      console.error('[UniErrorSDK] 初始化失败:', error);
      throw error;
    }
  }

  /**
   * 手动上报错误
   */
  private debug(message: string, data?: any) {
    if (this.configManager.getConfig().enableConsoleLog) {
      console.log(`[UniErrorSDK Debug] ${message}`, data || '');
    }
  }
  
  async reportError(error: Error | string, level: ErrorLevel = ErrorLevel.ERROR, customData?: Record<string, any>): Promise<void> {
    this.debug('开始上报错误', { error, level, customData });
    if (!this.isInitialized) {
      console.warn('[UniErrorSDK] SDK未初始化，请先调用init()方法');
      return;
    }

    const errorInfo: ErrorInfo = {
      level,
      message: typeof error === 'string' ? error : error.message,
      stack_trace: typeof error === 'object' ? error.stack : undefined,
      timestamp: Date.now(),
      platform: this.platformAdapter.getPlatformType(),
      device_info: await this.platformAdapter.getDeviceInfo(),
      user_behavior: this.errorCollector.getUserBehavior(),
      performance_data: await this.platformAdapter.getPerformanceData(),
      custom_data: customData
    };

    await this.errorReporter.report(errorInfo);
    this.debug('错误上报完成');
  }

  /**
   * 记录自定义用户行为
   */
  recordCustomBehavior(type: string, data: Record<string, any>): void {
    if (!this.isInitialized) {
      console.warn('[UniErrorSDK] SDK未初始化，请先调用init()方法');
      return;
    }
    this.errorCollector.recordCustomBehavior(type, data);
  }

  /**
   * 记录用户点击行为（用于小程序和App）
   */
  recordClick(elementInfo: {
    type: string;
    id?: string;
    text?: string;
    [key: string]: any;
  }): void {
    if (!this.isInitialized) {
      console.warn('[UniErrorSDK] SDK未初始化，请先调用init()方法');
      return;
    }
    this.errorCollector.recordClick(elementInfo);
  }

  /**
   * 获取用户行为数据
   */
  getUserBehavior() {
    if (!this.isInitialized) {
      console.warn('[UniErrorSDK] SDK未初始化，请先调用init()方法');
      return [];
    }
    return this.errorCollector.getUserBehavior();
  }

  /**
   * 获取会话信息
   */
  getSessionInfo() {
    if (!this.isInitialized) {
      console.warn('[UniErrorSDK] SDK未初始化，请先调用init()方法');
      return null;
    }
    return this.errorCollector.getSessionInfo();
  }
}